<?php

namespace App\Controller\Admin;

use App\Model\AuthMenu;
use App\Model\AuthUser;
use App\Service\AdminAuthService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Psr\Http\Message\ResponseInterface;

/**
 * @Controller(prefix="/admin/menu")
 */
class AuthMenuController extends AdminBaseController
{



    /**
     * @Inject()
     * @var AdminAuthService
     */
    public $adminAuthService;



    /**
     * 菜单列表
     * @RequestMapping(path="menuList")
     * @return ResponseInterface
     */
    public function menuList()
    {

        $json = $this->adminAuthService->getAuthMenuByUid($this->uid());
        return $this->response->adminSuccess(['list' => $json]);

    }


    /**
     * 新增菜单
     * @RequestMapping(path="addMenu")
     * @return ResponseInterface
     */
    public function addMenu()
    {

        $params = $this->request->post();

        $pid = $params['pid'] ?? 0;

        if ($pid > 0) {
            $pInfo = AuthMenu::where(['id' => $pid, 'status' => 1])->first();
            if (is_null($pInfo)) {
                return $this->response->adminFail('上级ID没有或者已禁用');
            }

            $level = ['menuDir' => 1, 'menu' => 2, 'button' => 3];

            if ($level[$params['type']] <= $level[$pInfo['type']]) {
                return $this->response->adminFail('菜单结构错误，层级规则为：菜单目录->菜单->按钮功能');
            }


        }

        $where = [
            ['name', '=', $params['name']],
            ['path', '=', $params['path'], 'or'],
        ];
        $exists = AuthMenu::where($where)->exists();

        if ($exists) {
            return $this->response->adminFail('name 或者 path 已经存在请勿重复添加');
        }

        $data = [
            'pid' => $pid,
            'name' => $params['name'] ?? '',
            'path' => $params['path'] ?? '',
            'title' => $params['title'] ?? '',
            'type' => $params['type'] ?? '',
            'menu_type' => $params['menuType'] ?? '',
            'component' => $params['component'] ?? '',
            'url' => $params['url'] ?? '',
            'keepalive' => $params['keepalive'] ?? 1,
            'status' => $params['status'] ?? 1,
            'sort' => $params['sort'] ?? 0,
            'icon' => $params['icon'] ?? '',
            'update_time' => time(),
        ];

        $rel = AuthMenu::insert($data);
        if ($rel) {
            return $this->response->adminSuccess();
        } else {
            return $this->response->adminFail();
        }


    }


    /**
     * 编辑菜单
     * @RequestMapping(path="editMenu")
     * @return ResponseInterface
     */
    public function editMenu()
    {
        $params = $this->request->post();

        $pid = $params['pid'] ?? 0;
        $id = $params['id'] ?? 0;
        if ($pid == $id) {
            return $this->response->adminFail('不能自己作为自己的上级');
        }

        if ($pid > 0) {
            $pInfo = AuthMenu::where(['id' => $pid, 'status' => 1])->first();
            if (is_null($pInfo)) {
                return $this->response->adminFail('上级ID没有或者已禁用');
            }
            $list = AuthMenu::get()->toArray();
            $subIds = AuthMenu::findSubIdS($list, $id);
            if (in_array($pid, $subIds)) {
                return $this->response->adminFail('不能选用下级作为自己的上级');
            }
            $level = ['menuDir' => 1, 'menu' => 2, 'button' => 3];
            if ($level[$params['type']] <= $level[$pInfo['type']]) {
                return $this->response->adminFail('菜单结构错误，层级规则为：菜单目录->菜单->按钮功能，当前选择父级为：' . $pInfo['type']);
            }
        }

        $where = [
            ['name', '=', $params['name']],
            ['path', '=', $params['path'], 'or'],
        ];
        $exists = AuthMenu::where($where)->exists();

        if ($exists) {
            return $this->response->adminFail('name 或者 path 已经存在,请修改为新的');
        }
        $data = [
            'pid' => $pid,
            'name' => $params['name'] ?? '',
            'path' => $params['path'] ?? '',
            'title' => $params['title'] ?? '',
            'type' => $params['type'] ?? '',
            'menu_type' => $params['menuType'] ?? '',
            'component' => $params['component'] ?? '',
            'url' => $params['url'] ?? '',
            'keepalive' => $params['keepalive'] ?? 1,
            'status' => $params['status'] ?? 1,
            'sort' => $params['sort'] ?? 0,
            'icon' => $params['icon'] ?? '',
            'update_time' => time(),
        ];
        $rel = AuthMenu::where(['id' => $id])->update($data);
        if ($rel) {
            return $this->response->adminSuccess();
        } else {
            return $this->response->adminFail();
        }

    }


    /**
     * 删除菜单以及所有下级菜单
     * @RequestMapping(path="delMenu")
     * @return ResponseInterface
     */
    public function delMenu()
    {

        $adminInfo = AuthUser::where(['id' => $this->uid(), 'status' => 1])->first();

        if ($adminInfo['super_admin'] != 1) {
            return $this->response->adminFail('删除菜单需超级管理员操作，请联系技术人员');
        }

        $id = $this->request->post('id');

        $data = AuthMenu::select(['id', 'pid'])->where(['id'=>$this->request->post('id')])->get()->toArray();
        $subIds = AuthMenu::findSubIdS($data, $id);

        $where = array_merge([$id], $subIds);

        $rel = AuthMenu::whereIn('id', $where)->delete();

        if ($rel) {
            return $this->response->adminSuccess();
        } else {
            return $this->response->adminFail();
        }

    }


    /**
     * 修改缓存状态
     * @RequestMapping(path="keepLiveStatus")
     * @return ResponseInterface
     */
    public function keepLiveStatus()
    {
        $id = $this->request->post('id');
        $keepalive = $this->request->post('keepalive', 1);

        $rel = AuthMenu::where(['id' => $id])->update(['keepalive' => $keepalive, 'update_time' => time()]);
        if ($rel) {
            return $this->response->adminSuccess();
        } else {
            return $this->response->adminFail();
        }

    }

    /**
     * @RequestMapping(path="changeStatus")
     * @return ResponseInterface
     */
    public function changeStatus(){
        $id = $this->request->post('id');
        $keepalive = $this->request->post('status', 1);

        $rel = AuthMenu::where(['id' => $id])->update(['status' => $keepalive, 'update_time' => time()]);
        if ($rel) {
            return $this->response->adminSuccess();
        } else {
            return $this->response->adminFail();
        }
    }
}